import React, { memo, useState, useEffect } from 'react';

import {
  Button,
  Timeline,
  Space,
  Popconfirm,
  message,
  Select,
  Spin,
  Tooltip,
  Upload,
  Image,
} from 'antd';
import { CloseCircleOutlined, LinkOutlined, ZoomInOutlined } from '@ant-design/icons';
import { FooterToolbar } from '@ant-design/pro-layout';

import { ModalForm, ProFormText, ProFormSelect, ProFormTextArea } from '@ant-design/pro-form';
import {
  ProFormDateTimePicker,
  ProFormDatePicker,
  ProFormUploadButton,
} from '@ant-design/pro-form';
import request from '@/utils/request';
import ProDescriptions from '@ant-design/pro-descriptions';
import moment from 'moment';

let allTrackPath = [];
const Track = memo((props) => {
  const { data = {}, status = [], actionRef, statusVlueEumn, getProjectCount } = props;

  const [isTrackFormShow, setIsTrackFormShow] = useState(false);
  const [trackInfo, setTrackInfo] = useState({});
  const [trackInfoLoading, setTrackInfoLoading] = useState(null);

  const [visible, setVisible] = useState(false);
  const [currentImgList, setCurrentImgList] = useState([]);
  const onTrackFinish = async (values) => {
    console.log(values);
    const res = await request.post('/project/saveTrackingRecord', {
      data: {
        ...values,
        projectId: data.id,
        resources: JSON.stringify(allTrackPath),
      },
    });
    if (res.success) {
      message.success('添加成功');
      setIsTrackFormShow(false);
      getProject();
    } else {
      if (res.message) {
        message.error(res.message);
      } else {
        message.error('添加失败');
      }
    }
  };

  const confirm = async (e) => {
    const res = await request.post('/project/removeTrackingRecord', {
      data: {
        id: e.id,
      },
    });
    if (res.success) {
      message.success('删除成功');
      getProject();
    } else {
      if (res.message) {
        message.error(res.message);
      } else {
        message.error('删除失败');
      }
    }
  };

  const cancel = () => {};

  const getProject = async () => {
    setTrackInfoLoading(true);
    const res = await request.post('/project/getProject', {
      data: {
        id: data.id,
      },
    });
    if (res.success) {
      setTrackInfoLoading(false);
      setTrackInfo(res.data);
    }
  };

  useEffect(async () => {
    if (data.id) {
      getProject();
    }
  }, [data]);

  const colors = ['#000', 'orange', 'blue', '#ccc', 'red', 'purple', 'green', 'yellow', '#1890ff'];

  const colors2 = {
    BUSINESS_LEADS: '#000',
    PROPOSAL_QUOTATION: 'orange',
    PROJECT_BIDDING: 'blue',
    DEVELOPMENT: '#ccc',
    DELIVERY: 'red',
    ACCEPTANCE: 'purple',
    AFTER_SALES: 'green',
    COMPLETE: 'yellow',
    BUSINESS_TERMINATION: '#1890ff',
  };

  const allowedFileTypes = [
    'jpg',
    'jpeg',
    'png',
    'gif',
    'doc',
    'docx',
    'xlsx',
    'ppt',
    'pptx',
    'txt',
  ]; // 允许的文件类型

  const checkFileType = (file) => {
    const fileName = file.name.toLowerCase();
    const extension = fileName.split('.').pop(); // 获取文件扩展名
    return allowedFileTypes.includes(extension);
  };

  const getImgListByRes = (res) => {
    const imgList = [];
    res.map((item) => {
      if (
        item.path?.endsWith('jpg') ||
        item.path?.endsWith('jpeg') ||
        item.path?.endsWith('png') ||
        item.path?.endsWith('gif')
      ) {
        imgList.push('/api/resource/preview?path=' + item.path);
      }
    });
    return imgList;
  };

  const getDocListByRes = (res) => {
    const fileList = [];
    res.map((item) => {
      if (
        item.path?.endsWith('xlsx') ||
        item.path?.endsWith('doc') ||
        item.path?.endsWith('docx') ||
        item.path?.endsWith('ppt') ||
        item.path?.endsWith('pptx') ||
        item.path?.endsWith('txt')
      ) {
        fileList.push({
          name: item.path?.split('/')[1],
          src: item.path,
        });
      }
    });
    return fileList;
  };

  return (
    <>
      <div
        style={{
          background: '#fff',
          borderBottom: '1px solid #f2f2f2',
          padding: '10px 30px',
          fontWeight: 'bold',
          fontSize: 16,
        }}
      >
        <span>项目详情</span>
        <Button
          style={{ float: 'right', position: 'relative', bottom: 3 }}
          onClick={(e) => {
            setIsTrackFormShow(true);
          }}
          key="primary"
          type="primary"
        >
          提交记录
        </Button>
      </div>

      <div style={{ background: '#fff', padding: '10px 30px 30px 30px' }}>
        <ProDescriptions column={4}>
          <ProDescriptions.Item label="项目名称" valueType="text">
            {trackInfo.name}
          </ProDescriptions.Item>
          <ProDescriptions.Item label="项目体量" valueType="text">
            {trackInfo.scale}万
          </ProDescriptions.Item>
          <ProDescriptions.Item label="项目状态" valueType="text">
            {statusVlueEumn[trackInfo.status]?.text}
          </ProDescriptions.Item>
          <ProDescriptions.Item label="客户名称" valueType="text">
            {trackInfo.custName}
          </ProDescriptions.Item>
          <ProDescriptions.Item label="当前跟进人" valueType="text">
            {trackInfo.chargePerson}
          </ProDescriptions.Item>
          <ProDescriptions.Item label="重点事项" valueType="text">
            {trackInfo.keyPoints}
          </ProDescriptions.Item>
          <ProDescriptions.Item label="备注" valueType="text">
            {trackInfo.remarks}
          </ProDescriptions.Item>
          <ProDescriptions.Item label="创建时间" valueType="text">
            {trackInfo.createAt}
          </ProDescriptions.Item>
          <ProDescriptions.Item valueType="text" label="项目描述">
            {trackInfo.desc}
          </ProDescriptions.Item>
        </ProDescriptions>

        <ModalForm
          initialValues={{
            createAt: moment(),
            status: trackInfo.status,
          }}
          title="跟踪记录"
          width={500}
          visible={isTrackFormShow}
          onFinish={onTrackFinish}
          onVisibleChange={(visible) => {
            allTrackPath = [];
            return !visible && setIsTrackFormShow(false);
          }}
          validateTrigger="onBlur"
          layout="horizontal"
          labelCol={{ span: 5 }}
          modalProps={{ destroyOnClose: true }}
        >
          <ProFormSelect
            rules={[{ required: true, message: '请选择项目状态' }]}
            name="status"
            label="项目状态"
            placeholder="请选择项目状态"
          >
            <Select listHeight={300}>
              {status.map((option, index) => (
                <Select.Option key={option.value} value={option.value}>
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <div
                      style={{
                        marginRight: 10,
                        background: colors[index],
                        width: 10,
                        height: 10,
                        borderRadius: '50%',
                        position: 'relative',
                      }}
                    >
                      <div
                        style={{
                          background: '#fff',
                          height: 5,
                          width: 5,
                          borderRadius: '50%',
                          position: 'absolute',
                          top: '50%',
                          left: '50%',
                          transform: 'translate(-50%,-50%)',
                        }}
                      ></div>
                    </div>
                    <span>{option.label}</span>
                  </div>
                </Select.Option>
              ))}
            </Select>
          </ProFormSelect>
          <ProFormText
            rules={[{ required: true, message: '请输入进展描述' }]}
            name="desc"
            label="进展描述"
          ></ProFormText>
          <ProFormTextArea
            rules={[{ required: true, message: '请输入详细记录' }]}
            name="detail"
            label="详细记录"
          ></ProFormTextArea>
          <ProFormDatePicker
            rules={[{ required: true, message: '请选择记录日期' }]}
            name="createAt"
            label="记录日期"
          ></ProFormDatePicker>
          <ProFormUploadButton
            // onChange={onFileChange}
            name="extraFile"
            label="附件"
            title="点击上传"
            fieldProps={{
              beforeUpload: async function (file) {
                if (!checkFileType(file)) {
                  message.error('只能上传图片以及文档内容');
                  return Upload.LIST_IGNORE; // 返回false以取消上传
                }
                var formData = new FormData();
                formData.append('file', file);
                const res = await request.post('/resource/upload', {
                  data: formData,
                });
                if (res.success) {
                  allTrackPath.push({
                    uid: file.uid,
                    path: res.data,
                  });
                }
                return false;
              },
              onRemove(file) {
                const index = allTrackPath.findIndex((item) => item.uid == file.uid);
                allTrackPath.splice(index, 1);
              },
            }}
          ></ProFormUploadButton>
        </ModalForm>
        <FooterToolbar style={{ minHeight: 50 }}>
          <Space>
            <Button
              onClick={() => {
                props.setIsShowTrack(false);
                actionRef.current.reload();
                getProjectCount();
              }}
              type="primary"
            >
              返回
            </Button>
          </Space>
        </FooterToolbar>
      </div>
      <div
        style={{ position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%,-50%)' }}
      >
        <Spin w size="large" spinning={trackInfoLoading}></Spin>
      </div>

      {trackInfo.trackingRecords?.length ? (
        <div
          style={{
            background: '#fff',
            borderBottom: '1px solid #f2f2f2',
            padding: '10px 30px',
            fontWeight: 'bold',
            fontSize: 16,
            marginTop: 30,
          }}
        >
          <span>项目跟踪记录</span>
        </div>
      ) : null}
      {trackInfo.trackingRecords?.length ? (
        <div style={{ background: '#fff', padding: 30 }}>
          <Timeline>
            {trackInfo.trackingRecords &&
              trackInfo.trackingRecords.map((item) => {
                return (
                  <Timeline.Item color={colors2[item.status]}>
                    <p style={{ fontSize: 16, fontWeight: 'bold' }}>
                      <span>
                        {item.createAt} {item.desc} {item.createBy}
                      </span>
                      <Popconfirm
                        title="确定删除该条记录吗?"
                        onConfirm={(e) => confirm(item)}
                        onCancel={cancel}
                        okText="确定"
                        cancelText="取消"
                      >
                        <CloseCircleOutlined style={{ color: '#000', marginLeft: 30 }} />
                      </Popconfirm>
                    </p>
                    <p>
                      <span>详细记录: </span>
                      {item.detail}
                    </p>
                    {item.resources && JSON.parse(item.resources).length != 0 && (
                      <p style={{ fontSize: 18, fontWeight: 'bold' }}>附件:</p>
                    )}
                    <div>
                      <div>
                        {getImgListByRes(JSON.parse(item.resources))?.length ? (
                          <Button
                            icon={<ZoomInOutlined />}
                            onClick={() => {
                              setVisible(true);
                              if (item.resources) {
                                setCurrentImgList(getImgListByRes(JSON.parse(item.resources)));
                              }
                            }}
                          >
                            点击预览附件图片
                          </Button>
                        ) : null}
                      </div>
                      <div>
                        {item.resources &&
                          getDocListByRes(JSON.parse(item.resources)).map((item) => {
                            return (
                              <div style={{ cursor: 'pointer', margin: '10px 0' }}>
                                <LinkOutlined
                                  onClick={(e) => {
                                    window.open(`/api/resource/download?path=${item.src}`);
                                  }}
                                />
                                <span
                                  onClick={(e) => {
                                    window.open(`/api/resource/download?path=${item.src}`);
                                  }}
                                >
                                  {item.name}
                                </span>
                              </div>
                            );
                          })}
                      </div>
                    </div>
                  </Timeline.Item>
                );
              })}
          </Timeline>
          {/* 图片预览 */}
          <div style={{ display: 'none' }}>
            <Image.PreviewGroup
              preview={{
                visible,
                onVisibleChange: (vis) => {
                  if (!vis) {
                    // 解决点击预览不同跟踪记录闪屏的问题
                    setCurrentImgList([]);
                  }
                  setVisible(vis);
                },
              }}
            >
              {currentImgList.map((item) => {
                return <Image src={item} />;
              })}
            </Image.PreviewGroup>
          </div>
        </div>
      ) : null}
    </>
  );
});

export default Track;
